package com.lizicloud.user.userRegister.service;

import com.lizicloud.application.dto.ApiResponse;
import com.lizicloud.user.userLogin.constants.LoginConstants;
import com.lizicloud.user.userRegister.dto.RegisterDTO;
import com.lizicloud.domain.model.User;
import com.lizicloud.infrastructure.persistence.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户注册服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RegisterService {
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    
    /**
     * 用户注册
     */
    @Transactional
    public ApiResponse<String> register(RegisterDTO registerDTO) {
        try {
            log.info("用户注册请求：用户账号={}", registerDTO.getUseraccount());
            
            // 1. 检查用户账号是否已存在
            User existingUser = userMapper.selectByUseraccount(registerDTO.getUseraccount());
            if (existingUser != null) {
                log.warn("用户账号已存在：用户账号={}", registerDTO.getUseraccount());
                return ApiResponse.error("用户账号已存在");
            }
            
            // 2. 创建新用户
            User newUser = new User();
            newUser.setUseraccount(registerDTO.getUseraccount()); // 用户账号用于登录
            newUser.setUsername(registerDTO.getUsername()); // 用户名用于显示
            newUser.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
            newUser.setRole(registerDTO.getRole());
            newUser.setStatus(LoginConstants.USER_STATUS_ENABLED); // 默认激活状态
            
            // 3. 保存用户
            int result = userMapper.insert(newUser);
            if (result > 0) {
                log.info("用户注册成功：用户账号={}", registerDTO.getUseraccount());
                return ApiResponse.success("注册成功");
            } else {
                log.error("用户注册失败：用户账号={}", registerDTO.getUseraccount());
                return ApiResponse.error("注册失败");
            }
            
        } catch (Exception e) {
            log.error("用户注册异常：用户账号={}, 错误={}", registerDTO.getUseraccount(), e.getMessage());
            return ApiResponse.error("注册失败，请稍后重试");
        }
    }
}